<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/7
 * Time: 1:51
 */

namespace app\api\controller\v15;

use app\api\controller\v2\Auth;
use app\common\cachemodel\Recode;
use app\common\cachemodel\Rectification as RectificationCacheModel;
use app\common\lib\Util;
use app\common\model\MessageCenter;

/**
 * @title 消息中心
 * @desc
 * @url
 * @version 1.10.2
 * Class Message
 * @package app\api\controller\v2
 */
class Message extends Auth
{
    /**
     * 消息列表
     * @return \think\response\Json
     * @throws \Exception
     */
    public function index()
    {
        $type = input('param.type/d');
        $page = input('param.page/d', 1);

        $MsgModel = new MessageCenter();

        $uid = $this->user['id'];
        $map['range'] = [['=', 0], ['=', $this->user['id']], 'or'];
        $map['status'] = ['neq', -1];
        $map['type'] = $type;

        // 获取当前用户的所有消息
        $data = $MsgModel->get_user_msg_id(['uid' => $uid, 'type' => $type, 'page' => $page]);
        $tmp = [];
        try
        {
            if ($data['data'])
            {
                foreach ($data['data'] as $k => $v)
                {
                    //若消息中心数据未删除,进行数据显示
                    if ($v['cid'] == 0)
                    {
                        $icon_url = \config('message.default');
                    } elseif ($v['cid'] == 1)
                    {
                        $icon_url = \config('message.rectification');
                    } elseif ($v['cid'] == 2)
                    {
                        $icon_url = \config('message.lucky_star');
                    } else
                    {
                        $icon_url = \config('message.default');
                    }
                    //替换文本
                    if ($v['ac_content'])
                    {
                        //评论内容最长显示30个
                        if (strlen($v['ac_content']) > 30)
                        {
                            $v['ac_content'] = mb_substr($v['ac_content'], 0, 30, 'utf8') . '...';
                        }
                        $replace_text = $v['ac_content'];
                    } elseif ($v['cr_content'])
                    {
                        //回复内容最长显示30个
                        if (strlen($v['cr_content']) > 30)
                        {
                            $v['cr_content'] = mb_substr($v['cr_content'], 0, 30, 'utf8') . '...';
                        }
                        $replace_text = $v['cr_content'];
                    } else
                    {
                        $replace_text = '';
                    }
                    //申诉状态  审核状态 0=》正常无违规 ，1=>未申诉，2=>未审核，3=>正常，4=>违规
                    if ($v['ac_check_status'])
                    {
                        switch ($v['ac_check_status'])
                        {
                            case 1:
                                $check_status = 1;
                                break;
                            case 2:
                                $check_status = 2;
                                break;
                            default :
                                $check_status = 0;
                                break;
                        }
                    } elseif ($v['cr_check_status'])
                    {
                        switch ($v['cr_check_status'])
                        {
                            case 1:
                                $check_status = 1;
                                break;
                            case 2:
                                $check_status = 2;
                                break;
                            default:
                                $check_status = 0;
                                break;
                        }
                    } else
                    {
                        $check_status = 0;
                    }

                    if ($v['target'] === 'local' && $v['link'] && $v['link'] !== 'empty' && Util::CheckAppVersion('2.6.0') !== '小')
                    {
                        $arr = parse_url($v['link']);
                        if (isset($arr['path']) && $arr['path'] === 'rectification_details')
                        {   // 生时校正
                            if (!empty($arr['query']))
                            {
                                $paramArr = $this->convertUrlArray($arr['query']);
                                $reid = $paramArr['id'];
                            } else
                            {
                                $reid = $v['reid'];
                                $v['link'] = $v['link'] . "?id={$v['reid']}";
                            }
                            $rec = current((new RectificationCacheModel())->getRecDetail($reid));
                            $reocdeStatus = (new Recode())->getInfoById($rec['rid']);
                            if ($reocdeStatus['status'] != 1)
                            {
                                $v['target'] = 'toast';
                                $v['link'] = "当前档案已删除\r\n不支持查看";
                            }
                        } elseif (isset($arr['query']))
                        {
                            $paramArr = $this->convertUrlArray($arr['query']);
                            if (isset($paramArr['rid']))
                            {
                                $recodeInfoOld = (new Recode())->getInfoById($paramArr['rid']);
                                if ($recodeInfoOld['status'] != 1)
                                {
                                    $v['target'] = 'toast';
                                    $v['link'] = '档案不存在！如已删除请去订单中查看结果。';
                                }
                            }
                        }
                    }

                    $link = htmlspecialchars_decode($v['link']);
                    if ($link === 'vip_center?from=1')
                    {
                        $link = 'vip_center?from=1&need_auth=2';
                    }
                    //反转义
                    $tmp[] = [
                        'id' => (int)$v['id'],
                        'title' => $v['title'],
                        'content' => $v['content'],
                        'link' => $link,
                        'target' => $v['target'],
                        'create_time' => $v['create_time'],
                        'icon_url' => $icon_url,
                        'is_read' => (int)$v['is_read'],
                        'complain_status' => (int)$check_status,
                        'replace_text' => $replace_text
                    ];
                }
            }
            $data['data'] = $tmp;
        }
        catch (\Exception $e)
        {
            \think\Log::write('获取消息中心列表失败:' . $e->getMessage() . '文件信息:[' . $e->getFile() . $e->getLine() . ']' . '--------用户id:' . $uid, 'log', true);
            $data = [];
        }

        //将数据根据创建时间排序
        if ($data['data'])
        {
            array_multisort(array_column($data['data'], 'id'), SORT_NUMERIC, SORT_DESC, $data['data']);
        }
        $data['num_list'] = (new MessageCenter())->getUnreadMsgNum($this->user['id']);
        return show(\config('code.success'), '成功', $data);
    }


    /**
     * 处理链接中的参数
     * @param $query
     * @return array
     */
    public function convertUrlArray($query)
    {
        $queryParts = explode('&', $query);
        $params = [];
        foreach ($queryParts as $param)
        {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        return $params;
    }
}
